package com.loveyukari.dao.impl;

import com.loveyukari.dao.PermissionDao;
import com.loveyukari.model.Permission;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class JdbcPermissionDao extends BaseDao implements PermissionDao {
    private class PermissionRowMapper implements RowMapper<Permission> {

        public Permission mapRow(ResultSet rs, int rowNum) throws SQLException {
            Permission permission = new Permission();
            permission.setId(rs.getInt("id"));
            permission.setName(rs.getString("name"));
            return permission;
        }

    }

    @Override
    public List<Permission> selectAll() {
        String sql = "select * from permission";
        List<Permission> list = this.getJdbcTemplate().query(sql, new PermissionRowMapper());
        return list;
    }

    @Override
    public List<Permission> selectByAuthId(int authId) {
        String sql = "select p.* from auth_permission ap,permission p where ap.auth_id = ? and p.id = ap.permission_id";
        List<Permission> list = this.getJdbcTemplate().query(sql, new PermissionRowMapper(), authId);
        return list;
    }

    @Override
    public Permission selectById(int id) {
        String sql = "select * from permission where id = ?";
        List<Permission> list = this.getJdbcTemplate().query(sql, new PermissionRowMapper(), id);
        if (list.isEmpty()){
            return null;
        }
        return list.get(0);
    }


    @Override
    public int countByAuthIdAndPermissionType(int authId, int permissionId) {
        String sql = "select count(*) from auth_permission ap where auth_id = ? and permission_id = ?";
        Integer count = this.getJdbcTemplate().queryForObject(sql, Integer.class, authId, permissionId);
        return count;
    }

    @Override
    public void insertAuthPermission(int authId, int permissionId) {
        String sql = "insert auth_permission (auth_id,permission_id) values(?,?)";
        this.getJdbcTemplate().update(sql,authId,permissionId);
    }

    @Override
    public void deleteAuthPermission(int authId, int permissionId) {
        String sql = "delete from auth_permission where auth_id = ? and permission_id = ?";
        this.getJdbcTemplate().update(sql,authId,permissionId);
    }

    @Override
    public List<Integer> selectAuthIdByPermission(int permissionId) {
        String sql = "select au.auth_id from auth_permission au left join auth a on au.auth_id = a.id where au.permission_id = ? order by a.score desc";
        List<Integer> list = this.getJdbcTemplate().queryForList(sql, Integer.class, permissionId);
        return list;
    }
}
